import React from 'react';
import { inject, observer } from 'mobx-react';
import { WeaTableNew, WeaLogView } from 'comsMobx';

let WeaTable = WeaTableNew.WeaTable;
import {
  WeaTop,
  WeaTab,
  WeaLeftTree,
  WeaLeftRightLayout,
  WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaPopoverHrm,
  WeaLocaleProvider,
} from 'ecCom';
import { Button, Modal, Tag } from 'antd';
import PageSpin from '../public/PageSpin';
import NoViewRightPage from '../public/NoViewRightPage';
import CoworkConstant from '../util/CoworkConstant';
import * as CoworkUtil from '../util/CoworkUtil';
import { toJS } from 'mobx';

const confirm = Modal.confirm;
const getLabel = WeaLocaleProvider.getLabel;
const WeaLogViewComp = WeaLogView.Component;
/**
 * 主题监控
 */
@inject('coworkItemMonitorStore')
@observer
class ItemMonitor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showLog: false,
      targetId: '',
    };
  }

  componentDidMount() {
    this.props.coworkItemMonitorStore.doInit();
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.location.key !== nextProps.location.key) {
      this.props.coworkItemMonitorStore.doInit();
    }
  }

  componentWillUnmount() {
    // 组件卸载时一般清理一些状态
    const { coworkItemMonitorStore } = this.props;
    coworkItemMonitorStore.clearStatus();
  }

  render() {
    const { coworkItemMonitorStore } = this.props;
    let {
      viewRightInitCompleted,
      viewRight,
      comsWeaTableStore,
      loading,
      form,
      topTab,
      selectedKey,
      conditioninfo,
      showSearchAd,
      sessionkey,
      logStore,
      status,
    } = coworkItemMonitorStore;
    const { logType, logSmallType } = toJS(status);
    conditioninfo = toJS(conditioninfo);
    const buttonsAd = [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@hsz50h@search`}
        type="primary"
        onClick={this.onTabSearch}
      >
        {getLabel(197, '搜索')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@9fl063@reset`}
        type="ghost"
        onClick={this.onTabReset}
      >
        {getLabel(2022, '重置')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@gy6cz0@cancel`}
        type="ghost"
        onClick={this.onTabCancel}
      >
        {getLabel(201, '取消')}
      </Button>,
    ];
    if (!viewRightInitCompleted) {
      return (
        <PageSpin
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_PageSpin@ubu9jc`}
        />
      );
    } else if (!viewRight) {
      return (
        <NoViewRightPage
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_NoViewRightPage@jua742`}
        />
      );
    }

    return (
      <div className="wea-cowork-itemMonitor">
        <WeaPopoverHrm
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaPopoverHrm@hgrpy3`}
        />
        <WeaRightMenu
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaRightMenu@e4cztw`}
          datas={this.getRightMenu()}
          onClick={this.onRightMenuClick}
        >
          <WeaTop
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaTop@a5t3ox`}
            title={getLabel(32576, '主题监控')}
            loading={loading}
            icon={CoworkConstant.icon}
            iconBgcolor={CoworkConstant.iconBgColor}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            onDropMenuClick={this.onRightMenuClick}
            buttons={this.getTopButtons()}
          >
            <WeaLeftRightLayout
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaLeftRightLayout@f4gr5k`}
              isNew={true}
              showLeft={false}
              leftCom={this.getLeftTree()}
            >
              <WeaTab
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaTab@3c4frm`}
                datas={topTab}
                keyParam="groupid"
                onChange={this.changeTab}
                selectedKey={selectedKey}
                searchType={['base', 'advanced']}
                searchsBaseValue={
                  form.isFormInit &&
                  form.getFormParams() &&
                  form.getFormParams().name
                }
                setShowSearchAd={this.setShowSearchAd}
                showSearchAd={showSearchAd}
                hideSearchAd={this.hideSearchAd}
                searchsAd={CoworkUtil.getSearchs(form, conditioninfo, () => {
                  coworkItemMonitorStore.setShowSearchAd(false);
                  coworkItemMonitorStore.doTableLoading();
                })}
                buttonsAd={buttonsAd}
                onSearch={coworkItemMonitorStore.doTableLoading}
                onSearchChange={this.onSearchChange}
              />
              <WeaTable
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaTable@pfif8p`}
                comsWeaTableStore={comsWeaTableStore}
                loading={loading}
                sessionkey={sessionkey}
                needScroll={true}
                hasOrder={true}
                getColumns={this.getNewColumns}
                onOperatesClick={this.onOperatesClick}
              />
            </WeaLeftRightLayout>
          </WeaTop>
        </WeaRightMenu>

        <WeaLogViewComp
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaLogViewComp@t7udjl`}
          visible={this.state.showLog}
          onCancel={this.onLogViewCancel}
          logStore={logStore}
          logType={logType}
          logSmallType={logSmallType}
          targetId={this.state.targetId}
        />
      </div>
    );
  }

  setShowSearchAd = bool =>
    this.props.coworkItemMonitorStore.setShowSearchAd(bool);
  hideSearchAd = () => this.props.coworkItemMonitorStore.setShowSearchAd(false);
  onSearchChange = v =>
    this.props.coworkItemMonitorStore.appendFormFields({ name: v });
  onLogViewCancel = () => this.setState({ showLog: false });

  onSearchLabelClick = () => {
    const { coworkItemMonitorStore } = this.props;
    coworkItemMonitorStore.setSelectedTreeKeys([]);
    coworkItemMonitorStore.clearFormFields();
    coworkItemMonitorStore.doTableLoading();
  };
  onTreeSelect = (treeKey) => {
    const { coworkItemMonitorStore } = this.props;
    let key = treeKey.substring(treeKey.indexOf('_') + 1);
    if (treeKey.indexOf('cMainType_') != -1) {
      // 类别
      coworkItemMonitorStore.clearFormFields();
    } else if (treeKey.indexOf('cType_') != -1) {
      // 版块
      coworkItemMonitorStore.setFormFields({ typeid: key }); // 设置高级查询条件的版块条件
    }

    coworkItemMonitorStore.setSelectedTreeKeys([treeKey]);

    coworkItemMonitorStore.setShowSearchAd(false);
    coworkItemMonitorStore.doTableLoading();
  };

  // 左侧树
  getLeftTree() {
    const { coworkItemMonitorStore } = this.props;
    const {
      selectedTreeKeys,
      leftTreeDatas,
      leftTreeTypes,
      leftTreeCounts,
    } = coworkItemMonitorStore;
    return (
      <WeaLeftTree
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaLeftTree@moqgj9`}
        datas={leftTreeDatas}
        counts={leftTreeCounts}
        countsType={leftTreeTypes}
        selectedKeys={selectedTreeKeys}
        onSearchLabelClick={this.onSearchLabelClick}
        onSelect={this.onTreeSelect}
      />
    );
  }

  // 切换tab事件
  changeTab = (theKey) => {
    const { coworkItemMonitorStore } = this.props;
    coworkItemMonitorStore.setSelectedKey(theKey);
    coworkItemMonitorStore.clearFormFields();
    this.executeSearch();
  };

  // top中的按钮
  getTopButtons() {
    let _disabled = !this.getTableSelectedValues().length;
    return [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@mrf205@delete`}
        type="primary"
        disabled={_disabled}
        onClick={this.batchCoworkItemMonitorDel}
      >
        {getLabel(32136, '批量删除')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@9q3ian@end`}
        type="primary"
        disabled={_disabled}
        onClick={this.batchCoworkItemMonitorEnd}
      >
        {getLabel(83246, '批量结束')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@ui4t84@totop`}
        type="primary"
        disabled={_disabled}
        onClick={this.setTop}
      >
        {getLabel(83247, '标记置顶')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@93p3xo@canceltop`}
        type="primary"
        disabled={_disabled}
        onClick={this.cancelTop}
      >
        {getLabel(24675, '取消置顶')}
      </Button>,
    ];
  }

  // 右键菜单
  getRightMenu() {
    let _disabled = !this.getTableSelectedValues().length;

    let btns = [];
    btns.push({
      key: 'search',
      icon: <i className="icon-coms-search" />,
      content: getLabel(197, '搜索'),
    });

    btns.push({
      key: 'batchCoworkItemMonitorDel',
      icon: <i className="icon-coms-Custom" />,
      content: getLabel(32136, '批量删除'),
      disabled: _disabled,
    });
    btns.push({
      key: 'batchCoworkItemMonitorEnd',
      icon: <i className="icon-coms-Custom" />,
      content: getLabel(83246, '批量结束'),
      disabled: _disabled,
    });
    btns.push({
      key: 'setTop',
      icon: <i className="icon-coms-Custom" />,
      content: getLabel(83247, '标记置顶'),
      disabled: _disabled,
    });
    btns.push({
      key: 'cancelTop',
      icon: <i className="icon-coms-Custom" />,
      content: getLabel(24675, '取消置顶'),
      disabled: _disabled,
    });
    btns.push({
      key: 'BTN_LOG',
      icon: <i className="icon-coms-Print-log" />,
      content: `${getLabel(83, '日志')}`,
      onClick: () => this.onRightMenuClick('BTN_LOG'),
    });

    btns.push({
      key: 'ShowCustomColumns',
      icon: <i className="icon-coms-Custom" />,
      content: getLabel(382660, '显示定制列'),
    });
    /*
		btns.push({ key: "collection", icon: <i className='icon-coms-Custom'/>, content: '收藏' });
		btns.push({ key: "help", icon: <i className='icon-coms-Custom'/>, content: '帮助' });
		*/
    return btns;
  }

  // 右键菜单事件绑定
  onRightMenuClick = (key) => {
    const { coworkItemMonitorStore } = this.props;
    if (key == 'search') {
      this.executeSearch();
    } else if (key == 'batchCoworkItemMonitorDel') {
      this.batchCoworkItemMonitorDel();
    } else if (key == 'batchCoworkItemMonitorEnd') {
      this.batchCoworkItemMonitorEnd();
    } else if (key == 'setTop') {
      this.setTop();
    } else if (key == 'cancelTop') {
      this.cancelTop();
    } else if (key == 'BTN_LOG') {
      this.setState({ showLog: true });
    } else if (key == 'ShowCustomColumns') {
      const { sessionkey, comsWeaTableStore } = toJS(coworkItemMonitorStore);
      comsWeaTableStore.setColSetVisible(sessionkey, true);
      comsWeaTableStore.tableColSet(sessionkey, true);
    }
  };

  // 执行搜索方法（也可用于刷新table）
  executeSearch = (initPage = false) => {
    const { coworkItemMonitorStore } = this.props;
    coworkItemMonitorStore.setShowSearchAd(false);
    initPage
      ? coworkItemMonitorStore.doTableLoading('', true)
      : coworkItemMonitorStore.doTableLoading();
  };

  batchCoworkItemMonitorDel = () => {
    this.executeButtonMethod('batchCoworkItemMonitorDel');
  };
  batchCoworkItemMonitorEnd = () => {
    this.executeButtonMethod('batchCoworkItemMonitorEnd');
  };
  setTop = () => {
    this.executeButtonMethod('setTop');
  };
  cancelTop = () => {
    this.executeButtonMethod('cancelTop');
  };
  executeButtonMethod(type, values) {
    const { coworkItemMonitorStore } = this.props;
    if (!values) {
      values = this.getTableSelectedValues();
    }
    let refreshTable = this.executeSearch.bind(this);
    let reloadTable = this.executeSearch.bind(this, true);
    switch (type) {
      case 'batchCoworkItemMonitorDel': {
        confirm({
          title: getLabel(131329, '信息确认'),
          content: (
            <p>
              {getLabel(4922, '确定删除选定的协作吗？', 'note')}
              <p style={{ color: 'red', paddingTop: 5 }}>
                {getLabel(
                  4827,
                  '注意：此操作会永久删除主题，以及主题中所有交流，不可恢复！',
                  'note',
                )}
              </p>
            </p>
          ),
          onOk() {
            coworkItemMonitorStore.batchCoworkItemMonitorDel(
              {
                coworkIds: values,
              },
              refreshTable,
            );
          },
          onCancel() {},
        });
        break;
      }
      case 'coworkItemMonitorDel': {
        confirm({
          title: getLabel(131329, '信息确认'),
          content: (
            <p>
              {getLabel(4922, '确定删除选定的协作吗？', 'note')}
              <p style={{ color: 'red', paddingTop: 5 }}>
                {getLabel(
                  4827,
                  '注意：此操作会永久删除主题，以及主题中所有交流，不可恢复！',
                  'note',
                )}
              </p>
            </p>
          ),
          onOk() {
            coworkItemMonitorStore.batchCoworkItemMonitorDel(
              {
                coworkIds: values,
              },
              reloadTable,
            );
          },
          onCancel() {},
        });
        break;
      }
      case 'batchCoworkItemMonitorEnd': {
        confirm({
          title: getLabel(125087, '确定要结束选择的协作？'),
          content: '',
          onOk() {
            coworkItemMonitorStore.batchCoworkItemMonitorEnd(
              {
                coworkIds: values,
              },
              reloadTable,
            );
          },
          onCancel() {},
        });
        break;
      }
      case 'reOpenCowork': {
        confirm({
          title: getLabel(4923, '确定要重新打开选择的协作？', 'note'),
          content: '',
          onOk() {
            coworkItemMonitorStore.reOpenCowork(
              {
                coworkId: values,
              },
              reloadTable,
            );
          },
          onCancel() {},
        });
        break;
      }
      case 'setTop': {
        coworkItemMonitorStore.batchCoworkItemMonitorTop(
          {
            coworkIds: values,
          },
          reloadTable,
        );
        break;
      }
      case 'cancelTop': {
        coworkItemMonitorStore.batchCoworkItemMonitorCancelTop(
          {
            coworkIds: values,
          },
          reloadTable,
        );
        break;
      }
    }
  }

  // 获得table选中行的主键值数组。若没选中任何一条，返回空数组
  getTableSelectedValues() {
    const { coworkItemMonitorStore } = this.props;
    const { comsWeaTableStore } = coworkItemMonitorStore;
    let values = comsWeaTableStore.selectedRowKeysAllPages;
    return values;
  }

  onTabSearch = () => {
    const { coworkItemMonitorStore } = this.props;
    coworkItemMonitorStore.setShowSearchAd(false);
    coworkItemMonitorStore.doTableLoading();
  };
  onTabReset = () => {
    const { coworkItemMonitorStore } = this.props;
    coworkItemMonitorStore.clearFormFields();
  };
  onTabCancel = () => {
    const { coworkItemMonitorStore } = this.props;
    coworkItemMonitorStore.setShowSearchAd(false);
  };

  // 自定义过滤渲染
  getNewColumns = (columns) => {
    let newColumns = '';
    newColumns = columns.map((column) => {
      let newColumn = column;
      newColumn.render = (text, record) => {
        let valueSpan =
          record[`${newColumn.dataIndex}span`] !== undefined
            ? record[`${newColumn.dataIndex}span`]
            : record[newColumn.dataIndex];
        let url = '';
        if (newColumn.dataIndex == 'name') {
          url = CoworkUtil.getViewCoworkUrl(record.id);
          return (
            <div className="cowork-monitor-list-name">
              <a
                className="wea-url-name"
                style={{ cursor: 'pointer' }}
                title={text}
                onClick={() => {
                  window.open(url);
                }}
              >
                {text}
              </a>
              {record.isTop == '1' && (
                <Tag
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_Tag@qzoruy`}
                  className="cowork-top"
                >
                  Top
                </Tag>
              )}
            </div>
          );
        }
        return (
          <div
            className="wea-url"
            dangerouslySetInnerHTML={{ __html: valueSpan }}
          />
        );
      };
      return newColumn;
    });
    return newColumns;
  };

  // 表格单元格转义
  onOperatesClick = (record, index, operate, flag) => {
    let coworkId = record.id;
    if (flag == 0) {
      // 删除
      this.executeButtonMethod('coworkItemMonitorDel', coworkId);
    } else if (flag == 1) {
      // 结束
      this.executeButtonMethod('batchCoworkItemMonitorEnd', coworkId);
    } else if (flag == 2) {
      // 重新打开
      this.executeButtonMethod('reOpenCowork', coworkId);
    } else if (flag == 3) {
      // 置顶
      this.executeButtonMethod('setTop', coworkId);
    } else if (flag == 4) {
      // 取消置顶
      this.executeButtonMethod('cancelTop', coworkId);
    } else if (flag == 5) {
      // 日志
      this.setState({ showLog: true });
    }
  };
}

export default WeaTools.tryCatch(
  React,
  props => (
    <WeaErrorPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaErrorPage@71q7sl`}
      msg={
        props.error
          ? props.error
          : getLabel(186, '对不起，该页面异常，请联系管理员！', 'error')
      }
    />
  ),
  { error: '' },
)(ItemMonitor);
